﻿using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using TodoApi.BaseData;
using TodoApi.Controllers.DTO;
using TodoApi.Models;

namespace TodoApi.Services
{
    public class StudentServices:IStudentServices
    {
        private readonly StudentContext _context;
        private readonly IMapper _mapper;
        public StudentServices(StudentContext context, IMapper mapper)
        {
            _context = context;
            _mapper = mapper;
        } 
        public  async Task<IEnumerable<StudentDTO>> Get()
        {
            var student = await _context.Student.Include(x=>x.Classes).ToListAsync();
            return _mapper.Map<IEnumerable<StudentDTO>>(student);
        }
        public async Task<ResultData> Update(StudentDTO studentDTO)
        {
            var student = _mapper.Map<Student>(studentDTO);
            //查看是否存在用户，有就更新没有就新增
            if (await _context.Student.AnyAsync(x => x.Id.Equals(student.Id)))
            {
                student.Classes = await _context.Set<Classes>().Where(x => x.Id == Guid.Parse(studentDTO.ClassId)).FirstAsync();
                student.AdmissionTime = await _context.Set<Student>().Where(x => x.Id == studentDTO.Id).Select(x => x.AdmissionTime).FirstOrDefaultAsync();
                _context.Student.Update(student);
                await _context.SaveChangesAsync();
                return new ResultData() { Code=200,Message="数据更新成功"};
            }
            else
            {
                //没有就新增
                student.Id = Guid.NewGuid();
                student.Classes = await _context.Set<Classes>().Where(x => x.Id == Guid.Parse(studentDTO.ClassId)).FirstAsync();
                student.AdmissionTime = DateTime.Now;
                await _context.Student.AddAsync(student);
                await _context.SaveChangesAsync();
                return new ResultData() { Code = 200, Message = "数据新增成功" };
            }
        }
    }
}
